package com.pingan.glue.gluegame.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pingan.glue.gluegame.aip.APIService;
import com.pingan.glue.gluegame.aip.domain.*;
import com.pingan.glue.gluegame.common.Constant;
import com.pingan.glue.gluegame.common.ErrorMessage;
import com.pingan.glue.gluegame.common.FaceExcelDto;
import com.pingan.glue.gluegame.common.utils.FileUtils;
import com.pingan.glue.gluegame.controller.form.FaceFieldForm;
import com.pingan.glue.gluegame.controller.form.FaceSearchForm;
import com.pingan.glue.gluegame.controller.form.SearchResponse;
import com.pingan.glue.gluegame.dao.FaceFieldDao;
import com.pingan.glue.gluegame.dao.FriendUserDao;
import com.pingan.glue.gluegame.entity.FaceFieldEntity;
import com.pingan.glue.gluegame.entity.FriendUserEntity;
import com.pingan.glue.gluegame.exception.BusinessException;
import com.pingan.glue.gluegame.service.ExcelService;
import com.pingan.glue.gluegame.service.FaceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class FaceServiceImpl implements FaceService {

    private final static Logger LOGGER = LoggerFactory.getLogger(FaceServiceImpl.class);

    @Value("${web.upload-path}")
    private String path;

    @Resource
    @Qualifier("baidu")
    private APIService apiService;

    @Resource
    private FaceFieldDao faceFieldDao;

    @Resource
    private FriendUserDao friendUserDao;

    @Resource
    private ExcelService excelService;

    @Override
    public FaceFieldEntity queryFaceFromDb(Long userId) {
        return faceFieldDao.queryByuserId(userId);
    }

    @Override
    public FaceFieldEntity faceDetect(String image,String path,Long userId) {
        LOGGER.info("FaceServiceImpl_faceDetect_service start");
        FaceFieldDto faceFieldDto = apiService.detect(image);
        if(faceFieldDto ==null){
            return new FaceFieldEntity();
        }
        FaceFieldEntity entity = faceFieldDto.build(path,userId);
        return entity;
    }

    @Override
    public String add(FaceFieldForm form) {
        LOGGER.info("FaceServiceImpl_add_param:{}", JSONObject.toJSONString(form));
        FaceAddDto dto = new FaceAddDto();
        dto.setImage(form.getFaceToken());
        dto.setGroup_id(form.getGroupId());
        dto.setUser_id(form.getUserId()+"");
        dto.setImage_type(Constant.IMAGES_TYPE_FACE_TOKEN);
        JSONObject json = apiService.add(dto);
        if (!"0".equals(json.getString("error_code"))){
            LOGGER.error("FaceServiceImpl_add_error:{}", json.toJSONString());
           throw new BusinessException(json.getString("error_code"),json.getString("error_msg"));
        }
        FaceFieldEntity entity = JSONObject.toJavaObject((JSON)JSONObject.toJSON(form),FaceFieldEntity.class);
        Integer i = faceFieldDao.insert(entity);
        LOGGER.info("FaceServiceImpl_update_result:{}",i);
        return "添加成功";
    }

    @Override
    public String update(FaceFieldForm form) {
        LOGGER.info("FaceServiceImpl_update_param:{}", JSONObject.toJSONString(form));
        FaceAddDto dto = new FaceAddDto();
        dto.setImage(form.getFaceToken());
        dto.setGroup_id(form.getGroupId());
        dto.setUser_id(form.getUserId()+"");
        dto.setImage_type(Constant.IMAGES_TYPE_FACE_TOKEN);
        JSONObject json = apiService.update(dto);
        if (!"0".equals(json.getString("error_code"))){
            LOGGER.error("FaceServiceImpl_update_error:{}", json.toJSONString());
            throw new BusinessException(json.getString("error_code"),json.getString("error_msg"));
        }
        FaceFieldEntity entity = JSONObject.toJavaObject((JSON)JSONObject.toJSON(form),FaceFieldEntity.class);
        entity.setUpdateTime(new Date());
        Integer i = faceFieldDao.updateByUserId(entity);
        LOGGER.info("FaceServiceImpl_update_result:{}",i);
        return "更新成功";
    }

    /**
     * 人脸登陆
     * @param image
     * @return
     */
    @Override
    public String loginFace(String image) {

        AIPResponse aip = getAipResponse(image);
        LOGGER.info("FaceServiceImpl_loginFace_aip_result:{}",JSONObject.toJSONString(aip));
        if (!"0".equals(aip.getError_code())){
            LOGGER.error("FaceServiceImpl_loginFace_error:{}",JSONObject.toJSONString(aip));
            throw new BusinessException(aip.getError_code(),aip.getError_msg());
        }

        APIFaceInfo result =aip.getResult();
        APIUserList user= result.getUser_list().get(0);
        Double score =user.getScore();
        if (score.compareTo(90.0)<=0){
            LOGGER.error("FaceServiceImpl_loginFace_error score {} lower 95:{}", score, JSONObject.toJSONString(aip));
            throw new BusinessException(ErrorMessage.FACE_LOGIN_ERROR_IMAGE);
        }

        return user.getUser_id();
    }

    private AIPResponse getAipResponse(String image) {
        FaceSearchDto dto = new FaceSearchDto();
        dto.setImage(image);
        dto.setImage_type(Constant.IMAGES_TYPE_BASE64);
        dto.setGroup_id_list(Constant.FEMALE_GROUP_ID_SUPPER_STAR+","+Constant.MALE_GROUP_ID_SUPPER_STAR);
        dto.setMax_user_num("1");
        dto.setQuality_control("NORMAL");
        return apiService.search(dto);
    }

    @Override
    public SearchResponse faceSearch(FaceSearchForm form, FriendUserEntity entity) {
        SearchResponse response = new SearchResponse();
        FaceFieldEntity faceField = queryFaceFromDb(entity.getUserId());
        FaceSearchDto dto = new FaceSearchDto();
        dto.setImage(faceField.getFaceToken());
        dto.setImage_type(Constant.IMAGES_TYPE_FACE_TOKEN);
        String groupId;
        if(Constant.MALE.equals(faceField.getGender())){
            groupId = Constant.FEMALE_GROUP_ID_SUPPER_STAR;
        }else if(Constant.FEMALE.equals(faceField.getGender())){
            groupId = Constant.MALE_GROUP_ID_SUPPER_STAR;
        }else{
            groupId = Constant.FEMALE_GROUP_ID_SUPPER_STAR+","+Constant.MALE_GROUP_ID_SUPPER_STAR;
        }
        dto.setGroup_id_list(groupId);
        dto.setMax_user_num("20");
        AIPResponse aip = apiService.search(dto);
        if (!"0".equals(aip.getError_code())){
            LOGGER.error("FaceServiceImpl_faceSearch_error:{}",JSONObject.toJSONString(aip));
            throw new BusinessException(aip.getError_code(),aip.getError_msg());
        }
        response.setFaceFieldEntity(faceField);
        List<FaceFieldEntity> ffes = aip.getResult().getUser_list().stream().map(user->{
            FaceFieldEntity e = faceFieldDao.queryByuserId(Long.parseLong(user.getUser_id()));
            if (e ==null) {
                LOGGER.error("FaceServiceImpl_faceSearch_error:数据库中不存在，百度人脸存在:"+user.getUser_id());
                return null;
            }
            e.setMobile(null);
            e.setScore(user.getScore());
            return e;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        response.setFaceFieldEntitys(ffes);
        return response;
    }


    @Override
    public void excel(String fileName) {
        List<FaceExcelDto> faces =  excelService.analysisExcel(fileName);
        faces.forEach(faceExcelDto -> {
            FriendUserEntity e = new FriendUserEntity();
            e.setStatus(1);
            e.setUsername(faceExcelDto.getUsername());
            e.setMobile(faceExcelDto.getMobile());
            e.setCreateTime(new Date());
            e.setUpdateTime(new Date());
            friendUserDao.insert(e);
            FriendUserEntity e1 = friendUserDao.queryByMobile(faceExcelDto.getMobile());
            String fileName1 = faceExcelDto.getPath();
            String uuid = UUID.randomUUID().toString();
            StringBuilder sb =new StringBuilder();
            StringBuilder fieldPath =new StringBuilder("/");
            sb.append(path).append("/").append(faceExcelDto.getMobile()).append(uuid).append(fileName1);
            fieldPath.append(faceExcelDto.getMobile()).append(uuid).append(fileName1);
            String image = FileUtils.upload("D:\\work\\download\\图库\\"+fileName1, sb.toString());
            FaceFieldEntity faceFieldEntity =  faceDetect(image,fieldPath.toString(),e1.getUserId());
            faceFieldEntity.setMobile(faceExcelDto.getMobile());
            faceFieldEntity.setOccupation(faceExcelDto.getOccupation());
            faceFieldEntity.setBloodType(faceExcelDto.getBloodType());
            faceFieldEntity.setConstellation(faceExcelDto.getConstellation());
            FaceFieldForm form = JSONObject.toJavaObject((JSON)JSONObject.toJSON(faceFieldEntity),FaceFieldForm.class);
            add(form);
        });
    }


}
